/**
 * @function 加密字符串
 * @param {string} text 被加密的字符串
 * @param {number} [front=3] 前半段明文长度，默认是 `3`
 * @param {number} [end=4] 后半段明文长度，默认是 `4`
 * @param {string} [symbol=*] 用于加密的字符，默认是 `*`
 * @returns {string}
 * @description
 * 字符串长度小于设置的明文长度或为空时，会返回传入值。
 * @example
 * const text = '18812341234'
 * encryptString(text) // -> 188****1234
 * encryptString(text, 2, 2, 'x') // -> 18xxxxxxx34
 */
export function encryptString(text, front = 3, end = 4, symbol = '*') {
  const length = String(text).length
  const plainTextLength = front + end

  if (!text || length < plainTextLength + 1) return text

  const encrypt = text.split('')
  encrypt.splice(
    front,
    length - plainTextLength,
    ...(new Array(length - plainTextLength).fill(symbol))
  )

  return encrypt.join('')
}

/**
 * @function 防抖
 * @param {Function} fn 方法
 * @param {number} [delay=1000] 防抖时间，默认是 `1000`
 * @returns
 */
export function debounce(fn, delay = 1000) {
  let timer

  return function () {
    const context = this
    const args = arguments

    clearTimeout(timer)

    timer = setTimeout(function () {
      fn.apply(context, args)
    }, delay)
  }
}

/**
 * @function 节流
 * @param {function} fn 方法
 * @param {number} [delay=1000] 节流时间，默认是 `1000`
 * @returns
 */
export function throttle(fn, delay = 1000) {
  let timer

  return function () {
    if (timer) return

    const context = this
    const args = arguments

    timer = setTimeout(function () {
      timer = null
    }, delay)

    fn.apply(context, args)
  }
}

/**
 * @function 生成哈希值
 * @param {string} str 字符串
 * @returns
 */
export function hashCode(str) {
  if (!str || !str.length) return 0

  let hash = 0, i, chr, len

  for (i = 0, len = str.length; i < len; i++) {
    chr = str.charCodeAt(i)
    hash = ((hash << 5) - hash) + chr
    hash |= 0
  }

  return hash
}

/**
 * @function 获取今天的日期
 * @param {string} [separator] 分隔符，默认是 "-"
 * @returns {string}
 */
export function getToday(separator = '-') {
  const today = new Date()
  return [today.getFullYear(), today.getMonth() + 1, today.getDate()].join(separator)
}
